#include "BinaryFileUtil.h"

BinaryFileUtil::BinaryFileUtil(const QString &filePath, QObject *parent)
    : QObject(parent), m_filePath(filePath), m_file(filePath)
{
    if (!m_file.exists()) {
        // 若文件不存在则创建
        if (m_file.open(QIODevice::WriteOnly)) {
            m_file.close();
        }
    }
}

bool BinaryFileUtil::writeBinary(const QByteArray &data, bool append)
{
    QFile::OpenMode mode = append ? QIODevice::Append : QIODevice::WriteOnly;
    if (!m_file.open(mode)) {
        qWarning() << "无法打开文件写入:" << m_filePath;
        return false;
    }
    m_file.write(data);
    m_file.close();
    return true;
}

QByteArray BinaryFileUtil::readBytes(qint64 length)
{
    if (!m_file.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开文件读取:" << m_filePath;
        return {};
    }

    m_file.seek(m_lastPos);
    QByteArray data = m_file.read(length);
    m_lastPos = m_file.pos();
    m_file.close();
    return data;
}

QByteArray BinaryFileUtil::readUntilByte(char stopByte)
{
    if (!m_file.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开文件读取:" << m_filePath;
        return {};
    }

    m_file.seek(m_lastPos);
    QByteArray result;
    char c;
    while (m_file.getChar(&c)) {
        result.append(c);
        if (c == stopByte) break;
    }
    m_lastPos = m_file.pos();
    m_file.close();
    return result;
}

void BinaryFileUtil::resetReadPos()
{
    m_lastPos = 0;
}
void BinaryFileUtil::setReadPos(const qint64 pos)
{
    m_lastPos = pos;
}
qint64 BinaryFileUtil::currentPos() const
{
    return m_lastPos;
}



///demo
BinaryFileUtil util("test.bat");

// 写入
// QByteArray data;
// data.append((char)0x01);
// data.append((char)0x02);
// data.append((char)0x03);
// data.append((char)0xFF);
// util.writeBinary(data);
// // 读取指定长度
// QByteArray firstTwo = util.readBytes(2);
// qDebug() << "前两个字节:" << firstTwo.toHex();
// // 继续读取到 0xFF
// QByteArray untilFF = util.readUntilByte((char)0xFF);
// qDebug() << "读到0xFF为止:" << untilFF.toHex();
// // 再次读取（文件尾无内容）
// QByteArray next = util.readBytes(2);
// qDebug() << "后续读取:" << next.toHex();
